package org.example.service.impl;

import org.example.dao.UserDao;
import org.example.dao.impl.UserDaoImpl;
import org.example.entity.User;
import org.example.other.ErrorEnum;
import org.example.other.ServiceException;
import org.example.service.UserService;
import org.example.util.DruidUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
    // 组合UserDao
    UserDao userDao;
    // 用构造方式初始化userDao
    public UserServiceImpl() {
        this.userDao = new UserDaoImpl();
    }
    @Override
    public User login(User user) throws SQLException {
        Connection conn = null;
        try {
            conn = DruidUtil.getConnection();
            User one = userDao.selectByAccount(conn, user.getAccount());
            if (one == null) {
                // 判定为账号不存在
                throw new ServiceException(ErrorEnum.ACCOUNT_NOT_EXISTS);
            }else if (!one.getPassword().equals(user.getPassword())) {
                // 判定为密码错误
                throw new ServiceException(ErrorEnum.PASSWORD_ERROR);
            }else if (one.getStatus() == 1) {
                // 判定为账号被禁用
                throw new ServiceException(ErrorEnum.ACCOUNT_IS_DISABLED);
            }
            // 上面如果没有抛出异常, 判定为登录成功, 返回对象one
            return one;
        } finally {
            DruidUtil.closeConnection(conn);
        }
    }
}
